<template>
  <div class="showBox equipment">
    <div class="head">
      <selectStore @handleChange="optionChange"/>
    </div>
    <div class="status" v-loading="devicesLodings">
      <div class="item" v-if="showPercentage">
        <p class="title">设备</p>
        <div class="box" >
          <div class="bar addEquipment__bar">
            <el-progress  style="font-weight: bold;" type="circle" :percentage="Math.round((statusListonlineNums/statusListTotalNums)*100>100?100:(statusListonlineNums/statusListTotalNums)*100)" color="#409EFF" :stroke-width="6" :width="100"></el-progress>
            <span class="bar__span" style="">在线率</span>
          </div>
          <div class="info">
            <p>在线(台)</p>
            <p>
              <span style="font-weight:800;font-size:17px;color:#000000">{{statusListonlineNums}}</span>/{{statusListTotalNums}}
            </p>
          </div>
        </div>
      </div>
      <div class="item" v-for="(item,index) in statusList" :key="index" v-if="showPercentage">
        <p class="title">{{item.type_name}}</p>
        <div class="box">
          <div class="bar addEquipment__bar">
            <el-progress style="font-weight: bold;" type="circle" :percentage="Math.round((item.online_nums/item.total_nums)*100>100 ? 100:(item.online_nums/item.total_nums)*100)" :color="item.color"  :stroke-width="6" :width="100"></el-progress>
            <span class="bar__span" style="">在线率</span>
          </div>

          <div class="info">
            <p>在线(台)</p>
            <p>
              <span style="font-weight:800;font-size:17px;color:#000000">{{item.online_nums}}</span>/{{item.total_nums}}
            </p>
          </div>

        </div>
      </div>
      <div v-if="!showPercentage" style="text-align: center; line-height: 140px">
        无设备信息
      </div>
    </div>

    <div class="table">
      <div class="tableBar">
        <el-row class="scanner">
          <el-col :span="2" class="item">
            <el-button size="mini" type="primary" round icon="el-icon-plus" @click="addItem('添加')">添加设备</el-button>
          </el-col>
          <el-col :span="6" class="item">
            <p>设备类型</p>
            <el-select v-model="deviceTypeCode" clearable size='small' placeholder="请选择设备类型">
              <el-option
                v-for="item in deviceModelList"
                :key="item.typeUuid"
                :label="item.typeName"
                :value="item.typeUuid">
              </el-option>
            </el-select>
          </el-col>

          <el-col :span="6" class="item">
            <p>设备名称</p>
            <el-input v-model="deviceName"  placeholder="请输入设备名称"></el-input>
          </el-col>

          <el-col :span="6" class="item">
            <p>区域</p>
            <el-input v-model="takeArea"  placeholder="请输入设备区域"></el-input>
          </el-col>

          <el-col :span="2" class="item">
            <el-button size="mini" type="primary" round @click="getData">搜索</el-button>
          </el-col>
        </el-row>
      </div>
      <el-table :data="tableData" size="mini"  v-loading="loadings">
        <el-table-column label="设备名称" prop="deviceName"></el-table-column>
        <el-table-column label="设备编号" prop="deviceNo"></el-table-column>
        <el-table-column label="在线状态" prop="deviceState">
          <template slot-scope="scope">
            {{scope.row.deviceState?'在线':'离线'}}
          </template>
        </el-table-column>
        <el-table-column label="设备型号" prop="deviceModel" ></el-table-column>
        <el-table-column label="设备路径" prop="deviceIp" ></el-table-column>
        <el-table-column label="端口号" prop="devicePort" ></el-table-column>
        <el-table-column label="账号" prop="deviceUser" ></el-table-column>
        <el-table-column label="门店名称" prop="orgName" ></el-table-column>
        <el-table-column label="设备类型" prop="typeName" ></el-table-column>
        <el-table-column label="拍摄区域" prop="takeArea" ></el-table-column>
        <el-table-column label="状态" prop="useState" >
          <template slot-scope="scope">
            {{scope.row.useState?'启用':'停用'}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" >
          <template slot-scope="scope">
            <el-button  size="mini" type="primary" plain round @click="getRefresh(scope.row)">刷新</el-button>
            <el-button  size="mini" type="primary" round style="margin-left: 5px"  @click="handleUpdateItem(scope.row, '修改')">编辑</el-button>
            <el-button  size="mini" round style="margin-left: 5px"  @click="open(scope.row)">{{scope.row.useState?'停用':'启用'}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="paging">
      <el-button v-if="tableData.length" size="mini"  type="primary" plain round @click="getRefresh()">全部刷新</el-button>
      <el-pagination
        @size-change="SizeChange"
        @current-change="CurrentChange"
        :page-sizes="[10, 20, 30, 50, 100]"
        :current-page="1"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >

      </el-pagination>
    </div>

    <el-dialog
      :title="`${title}设备`"
      :visible.sync="isAdd"
      :before-close="handleClose"
      width="50%"
      top="10vh"
    >
      <el-form class="smartShopDialogForm" :model="addItemObj" label-position="right" :rules="rules" ref="ruleForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备编号" label-width="120" prop="deviceNo">
              <el-input size="small" v-model="addItemObj.deviceNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" label-width="120" prop="deviceName">
              <el-input size="small" v-model="addItemObj.deviceName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备描写" label-width="120" prop="description">
              <el-input size="small" v-model="addItemObj.description"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号" label-width="120" prop="deviceModel">
              <el-input size="small" v-model="addItemObj.deviceModel"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备路径" label-width="120" prop="deviceIp">
              <el-input size="small" v-model="addItemObj.deviceIp"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口号" label-width="120" prop="devicePort"
              :rules="[
             {pattern: /^[0-9]*$/, trigger: 'blur', message: '端口号只能输入数字'},
             {required: true, trigger: 'blur',pattern: /\S/,message: '请输入端口号'}
             ]"
            >
              <el-input size="small" v-model="addItemObj.devicePort"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="账号" label-width="120" prop="deviceUser">
              <el-input size="small" v-model="addItemObj.deviceUser"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" label-width="120" prop="deivcePassword">
              <el-input size="small" v-model="addItemObj.deivcePassword"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备类型" label-width="120" prop="typeUuid">
              <el-select v-model="addItemObj.typeUuid">
                <el-option v-for="item in deviceModelList" :key="item.typeUuid" :label="item.typeName" :value="item.typeUuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拍摄区域" label-width="120" prop="takeArea">
              <el-input size="small" v-model="addItemObj.takeArea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属门店" label-width="120" prop="orgUuid">
              <el-select v-model="addItemObj.orgUuid" @change='changeOrg'>
                <el-option v-for="item in storeOptions" :key="item.orgSeq" :label="item.orgName" :value="item.orgSeq"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" label-width="120">
              <el-select v-model="addItemObj.useState">
                <el-option v-for="item in [{id:0,state:0},{id:1,state:1}]" :key="item.id" :label="item.state?'启用':'停用'" :value="item.state"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer" >
      <el-button @click="handleClose" round size="mini">取 消</el-button>
      <el-button type="primary" round @click="handleAddItem" size="mini">提交</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
  import {queryAllDeviceType, queryDeviceManage, refresh, updateDeviceState, queryOrgChildById, updateDeviceInfo, addDevice,getDevicesSatistics, getDeviceInfo} from '@/api/deviceManage'
  import selectStore from '../components/selectStore'
  export default {
    components: {selectStore},
    props: {},
    data() {
      return {
        devicesLodings: false,
        showPercentage: false,
        options:[],
        value:[],
        deviceTypeCode: '',
        deviceName: '',
        takeArea: '',
        orgSeq:'',
        deviceModelList: [],
        statusListTotalNums: '',
        statusListonlineNums: '',
        statusList:[
          {
            staUuid:'',
            color:'#E6A23C',
            totalNums: '',
            onlineNums: ''
          },
        ],
        tableData:[],
        pageSize:10,
        currentPage:1,
        total:0,
        addItemObj:{
          useState: 1,
        },
        title: '',
        isAdd:false,
        loadings:false,
        storeOptions:[]
      };
    },
    watch: {},
    methods: {
      //关闭编辑窗口
      handleClose() {
        this.isAdd=false
        this.addItemObj = {
          useState: 1,
        }
      },
      //编辑设备
      async handleUpdateItem(row,val) {
        this.title = val;
        this.isAdd=true;
        let data = await getDeviceInfo({
          deviceUuid: row.deviceUuid
        })
        if(data.result) {
          this.addItemObj = data.result
        }

      },
      //添加设备
       handleAddItem() {
        this.$refs.ruleForm.validate(async valid => {
          if (valid) {
            let data = this.title === '添加' ? await addDevice(this.addItemObj) : await updateDeviceInfo(this.addItemObj)
            if (data.code === 1) {
              this.$message({
                type: 'success',
                message: `${this.title}设备成功!`
              });
              this.addItemObj = {
                useState: 1,
              }
              this.isAdd = false
              this.getData()
              return
            }
            this.isAdd = false
            this.$message({
              type: 'error',
              message: data.message
            });
          }
        })
      },
      changeOrg(val) {
        this.storeOptions.map(item => {
          if(item.orgSeq === val) {
            return this.addItemObj.orgName = item.orgName
          }
        })
      },
      //刷新设备
      async getRefresh(val) {
        this.loadings=true;
        let data = await refresh({
          deviceUuid: !!val ? val.deviceUuid : ''
        })
        this.loadings=false;
        if(data.code === 1) {
          this.getData()
          this.getDevicesSatistics();
          this.$message({
            type: 'success',
            message: '刷新成功!'
          });
          return
        }
        this.$message({
          type: 'error',
          message: `${data.message}`
        });
      },
      optionChange(val){
        this.orgSeq=val[val.length-1];
        this.getData();
        this.queryOrgChildById();
        this.getDevicesSatistics()
      },
      //获取设备类型
      async getDeviceModelList() {
        let data =await queryAllDeviceType()
        if(data.code) {
          this.deviceModelList = data.records
        }
      },
      //设备查询
      async getData(){
        this.loadings = true;
        let {total,records} = await queryDeviceManage({
          size:this.pageSize,
          current:this.currentPage,
          condition:{
            orgSeq:this.orgSeq,
            deviceTypeUuid: this.deviceTypeCode,
            deviceName: this.deviceName,
            takeArea: this.takeArea
          }
        });
        if (records){
          this.tableData = records;
          this.total = total
          this.loadings = false;
          return
        }
        this.loadings = false;
        this.tableData = [];
        this.total = 0
      },
      SizeChange(size){
        this.pageSize=size;
        this.getData();
      },
      CurrentChange(current){
        this.currentPage=current;
        this.getData()
      },
      addItem(val){
        this.isAdd=true;
        this.title = val
      },
      //获取门店列表
      async queryOrgChildById() {
        let {records} = await queryOrgChildById({
          orgSeq:this.orgSeq,
        })
        if(records) {
          this.storeOptions = records
          return
        }
        this.storeOptions = []
      },
      //获取设备统计信息
      async getDevicesSatistics() {
        this.devicesLodings = true;
        let {records} = await getDevicesSatistics({
          orgSeq:this.orgSeq,
        })
        this.devicesLodings = false
        if(records.length >0) {
          let color = ['#E6A23C', '#F56C6C', '#909399', '#67C23A','#E6A23C', '#F56C6C', '#909399', '#67C23A'];
          this.statusList = records.slice(0);
          this.statusList.map((item,index) => {
            this.$set(item,'color',  color[index] )
          })
          let totalNums = this.statusList.map(item => item.total_nums).reduce((total, num) => total + num);
          let onlineNums = this.statusList.map(item => item.online_nums).reduce((total, num) => total + num);
          this.statusListTotalNums = totalNums
          this.statusListonlineNums = onlineNums
          this.showPercentage = true;
          return
        }
        this.showPercentage = false;
        this.statusList = []
        this.statusListonlineNums = 0
        this.statusListTotalNums = 0
      },
      //修改设备使用状态
      async open(row){
        this.loadings=true;
        let {code} = await updateDeviceState({
          deviceUuid: row.deviceUuid
        })
        if(code === 1) {
          setTimeout(()=>{
            this.loadings=false;
            row.useState=row.useState?0:1;
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
          },500)
          return
        }
        this.loadings=false;
        this.$message({
          type: 'error',
          message: '操作失败!'
        });
      }
    },
    created() {
      this.orgSeq=JSON.parse(localStorage.getItem('logininfo')).orgList[0].orgSeq||'';
    },
    mounted() {
      this.getData();
      this.getDeviceModelList();
      this.queryOrgChildById();
      this.getDevicesSatistics();
    },
    computed: {
      rules() {
            let ruleList = {}
            const ruleName = [
              {a:'deviceNo',b:'请输入设备编号（序列号）'},
              {a:'deviceName',b:'请输入设备名称'},
              {a:'description',b:'请输入设备描写'},
              {a:'deviceModel',b:'请输入设备型号'},
              {a:'deviceIp',b:'请输入设备路径'},
              {a:'deviceUser',b:'请输入账号'},
              {a:'deivcePassword',b:'请输入密码'},
              {a:'typeUuid',b:'请选择设备类型'},
              {a:'takeArea',b:'请输入拍摄区域'},
              {a:'orgUuid',b:'请输入所属门店'},
            ];
            ruleName.map(item => {
            this.$set(ruleList, `${item.a}`,
              [{required: true,  trigger: 'blur', message: `${item.b}`}, {
                required: true,
                trigger: 'change',
                message: `${item.b}`
              }],
            )
          })
            return ruleList;
      }
    }
  };
</script>
<style lang="scss" scoped>
  .showBox{
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    position: relative;
    .head{
      width: 100%;
      box-sizing: border-box;
      height: 50px;
      padding: 9px 0;
      display: flex;
      align-items: flex-end;
      position: relative;

      img{
        width: 30px;
        height: 32px;
        margin-right: 10px;
      }

      p{
        padding: 0 10px;
        font-size: 14px;
      }
    }

    .status{
      width: 100%;
      border: 1px solid #E4E7ED;
      border-radius: 6px;
      margin-bottom: 10px;
      padding: 10px;
      display: flex;
      flex-wrap: wrap;
      /*justify-content: space-between;*/
      align-items: center;

      .item{
        width: 180px;
        height: 100%;
        box-sizing: border-box;
        color: #909399;

        .title{
          height: 30px;
          width: 100%;
          text-align: left;
          line-height: 30px;
          font-size: 14px;
          font-weight: 500;
        }

        .box{
          width: 100%;
          display: flex;
          align-items: center;


          .bar{
            width: 60%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: center;
            position: relative;
            .bar__span{
              position: absolute;
              display:block;
              margin-top:4px;
              color:#909399;
              font-size: 15px;
              bottom: 30%;
              width: 100%;
              right: 0;

            }
          }

          .info{
            width: 40%;
            height: 100%;
            box-sizing: border-box;
            font-size: 14px;
            display: flex;
            align-items: flex-start;
            flex-direction: column;
            justify-content: center;
          }
        }

      }
    }

    .table{

      .tableBar{
        height: 35px;
        width: 100%;
        line-height: 35px;
        margin: 10px 0;


        .btn{
          height: 100%;
        }

        .scanner{
          height: 100%;
          display: flex;

          .item{
            height: 100%;
            line-height: 35px;
            font-size: 12px;

            &:nth-child(2){
              margin-left: 20px;
            }

            p{
              float: left;
              box-sizing: border-box;
            }

            .el-input, .el-select{
              width: calc(100% - 80px);
              margin-left: 10px;
            }
          }
        }
      }
    }

    .paging{
      width: 100%;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
</style>

<style lang="scss">
  .equipment{
    .el-table th>.cell{
      text-align:left
    }

    .el-form-item {
      margin-bottom: 8px;

      .el-form-item__label{
        width: 70px;
      }

      .el-input,.el-select{
        width: 70%;
      }

      .el-select{
        .el-input{
          width: 100%;
        }
      }
    }
    .addEquipment__bar{
      .el-progress__text{
        top: 35%;
      }
    }
  }
</style>
